package com.nowcoder.community.advice;/**
 * 功能描述
 *
 * @author 21775
 * @date 2022/09/22  16:28
 */

import com.nowcoder.community.utils.CommunityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *@ClassName ExceptionAdvice
 *@Description TODO 异常处理切面
 *@Author 21775
 *@Date 2022/9/22 16:28
 *@Version 1.0
 */
@Slf4j
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
    @ExceptionHandler({Exception.class})
    public void exceptionHandler(Exception exception, HttpServletRequest request, HttpServletResponse response){
        log.info("服务器发送异常"+exception.getMessage());
        for (StackTraceElement element : exception.getStackTrace()) {
            log.error(element.toString());
        }

        String xRequestedWith = request.getHeader("x-requested-with");
        try{
            if ("XMLHttpRequest".equals(xRequestedWith)) {
                response.setContentType("application/plain;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(CommunityUtil.getJSONString(1, "服务器异常!"));
            } else {
                response.sendRedirect(request.getContextPath() + "/error");
            }
        }catch (IOException e){
            log.info(e.getMessage());
        }

    }

}
